package vn.edu.ptithcm.pim.controller;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.ParameterizableViewController;

import vn.edu.ptithcm.pim.constant.Constants;
import vn.edu.ptithcm.pim.constant.UrlConstants;
import vn.edu.ptithcm.pim.dom.Project;
import vn.edu.ptithcm.pim.dom.Resource;
import vn.edu.ptithcm.pim.dom.ResourceCategory;
import vn.edu.ptithcm.pim.service.ProjectService;
import vn.edu.ptithcm.pim.service.ResourceCategoryService;
import vn.edu.ptithcm.pim.service.ResourceService;
import vn.edu.ptithcm.pim.service.UserService;
import vn.edu.ptithcm.pim.util.ParamUtil;

public class ResourceDetailController extends ParameterizableViewController {
	private UserService userService;
	private ProjectService projectService;
	private ResourceService resourceService;
	private ResourceCategoryService resourceCategoryService;
	Log log = LogFactory.getLog(ResourceDetailController.class);

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int pnum = ParamUtil.getInteger(request, "pnum", 0);
		long id = ParamUtil.getLong(request, "id", 0);
		Map<String, Object> bean = new HashMap<String, Object>();
		if (userService.isSignedIn(request)) {
			Project project = projectService.findByNumber(pnum);
			bean.put("project", project);
			String loginName = userService.getCurrentLogin(request);
			bean.put("user", userService.findByLoginName(loginName));
			bean.put("isSigned", true);
			bean.put("tab", "documents");
			bean.put(Constants.LOGIN_NAME, loginName);
			bean.put(Constants.USER_NAME, userService.getUsername(loginName));
			bean.put("isAdmin", userService.isAdmin(loginName));
			Resource resource = resourceService.findById(id);
			if (resource != null) {
				bean.put("resource", resource);
				ResourceCategory resourceCategory = resourceCategoryService
						.findById(resource.getCategoryId());
				bean.put("resourceCategory", resourceCategory);

				String fileName = resource.getOrignalName()
						+ resource.getType();

				String fileUrl = request.getRequestURL().toString() + "?pnum="
						+ pnum + "&id=" + resource.getResourceId()
						+ "&fileName=" + fileName;
				bean.put("fileUrl", fileUrl);

				if (ParamUtil.isRequestFile(request)) {
					String rootPath = request.getSession().getServletContext()
							.getRealPath("");
					int index = StringUtils.indexOf(rootPath, "pim");
					rootPath = rootPath.substring(0, index);

					response.setHeader("Content-disposition",
							"attachment; filename=" + fileName);
					response.setContentType("application/"
							+ resource.getType().substring(1));

					String path = resource.getPath();
					path = path.substring(1);
					path = path.replace('/', '\\');
					log.info("file full path:" + rootPath + path);
					InputStream is = new FileInputStream(rootPath + path);
					IOUtils.copy(is, response.getOutputStream());
					response.flushBuffer();
					response.getOutputStream().close();
				}
			}
			request.setAttribute("bean", bean);
		} else {
			String redirectLink = UrlConstants.RESOURCE_DETAIL_URL
					+ UrlConstants.HTM + "?pnum=" + pnum + "&id=" + id;
			request.getSession().setAttribute("redirectLink", redirectLink);
			response.sendRedirect(UrlConstants.HOME_PAGE_URL + UrlConstants.HTM);
		}

		return new ModelAndView(UrlConstants.RESOURCE_DETAIL_URL, "bean", bean);
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public ProjectService getProjectService() {
		return projectService;
	}

	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}

	public ResourceService getResourceService() {
		return resourceService;
	}

	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

	public ResourceCategoryService getResourceCategoryService() {
		return resourceCategoryService;
	}

	public void setResourceCategoryService(
			ResourceCategoryService resourceCategoryService) {
		this.resourceCategoryService = resourceCategoryService;
	}

}
